/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.security.admin;

import com.legendshop.oa.model.UserEntity;
import com.legendshop.oa.security.AbstractUserDetailsAuthenticationProvider;
import com.legendshop.oa.service.AdminAuthService;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Date;


/**
 * 管理员登录.
 */
public class AdminDaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
	
    private AdminAuthService adminAuthService;

    /**
     * 检查用户名密码
     */
	@Override
	   protected void additionalAuthenticationChecks(UserDetails userDetails, Authentication authentication) throws AuthenticationException {
	        if (authentication.getCredentials() == null) {
	            logger.debug("Authentication failed: no credentials provided");

	            throw new BadCredentialsException(messages.getMessage(
	                    "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
	        }
	    }

	@Override
	protected UserDetails retrieveUser(String username, Authentication authentication) throws AuthenticationException {
        UserDetails loadedUser = null;
        try {
        	UserEntity userEntity  = adminAuthService.loadUserByUsername(username, authentication.getCredentials().toString());
        	if(userEntity != null) {
				if(userEntity.getActiveTime() == null || userEntity.getActiveTime().after(new Date())){//没有设置有效期或者在有效期之内
					loadedUser = createUser(userEntity);
				}

        	}
        	
        } catch (UsernameNotFoundException notFound) {
            throw notFound;
        } catch (Exception repositoryProblem) {
            throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
        }

        if (loadedUser == null) {
            throw new AuthenticationServiceException(
                    "UserDetailsService returned null, which is an interface contract violation");
        }
        return loadedUser;
	}

		@Override
		public boolean supports(Class<?> authentication) {
			  return (AdminAuthenticationToken.class.isAssignableFrom(authentication)  );
		}

		@Override
		protected Authentication createSuccessAuthentication(Object principal,
				Authentication authentication, UserDetails user) {
	        // Ensure we return the original credentials the user supplied,
	        // so subsequent attempts are successful even with encoded passwords.
	        // Also ensure we return the original getDetails(), so that future
	        // authentication events after cache expiry contain the details
			AdminAuthenticationToken result = new AdminAuthenticationToken(principal,
	                authentication.getCredentials(), authoritiesMapper.mapAuthorities(user.getAuthorities()));
	        result.setDetails(authentication.getDetails());

	        return result;
		}
		

		public void setAdminAuthService(AdminAuthService adminAuthService) {
			this.adminAuthService = adminAuthService;
		}
		


	
}
